package com.shuyuwl.core.exception;

import com.shuyuwl.core.enums.ResultEnum;
import com.shuyuwl.core.support.ServerResponse;
import com.shuyuwl.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @Author ZChao
 * @Date 2019/9/27
 **/
@Slf4j
@RestControllerAdvice
@CrossOrigin(allowCredentials = "true",maxAge = 3600,allowedHeaders = "*",origins = "*")
public class GlobalExceptionHandler {

    /**
     * 捕获BaseException
     *
     * @param baseException
     * @return
     */
    @ExceptionHandler(value = SymServiceException.class)
    public ServerResponse handleServiceException(SymServiceException baseException) {
        return ServerResponse.createByErrorCodeMessage(baseException.getErrorCode(), baseException.getMessage());
    }

    /**
     * 系统未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ServerResponse<?> handleException(Exception e) {
        Integer code = ResultEnum.UNKOWN_ERROR.getCode();
        String msg = ResultEnum.UNKOWN_ERROR.getMsg();
        e.printStackTrace();
        return ServerResponse.createByErrorCodeMessage(code, msg);
    }

    /**
     * 系统未知运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    public ServerResponse<?> handleException(RuntimeException e) {
        Integer code = ResultEnum.UNKOWN_ERROR.getCode();
        String msg = ResultEnum.UNKOWN_ERROR.getMsg();
        e.printStackTrace();
        return ServerResponse.createByErrorCodeMessage(code, msg);
    }

    /**
     * 系统未知运行时异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ServerResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException exception) {

        Integer code = 2004001;
        BindingResult bindingResult = exception.getBindingResult();
        String msg = StringUtils.EMPTY;
        if (bindingResult.hasErrors()) {
            msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("数据验证-->: {}", msg);
        }
        return ServerResponse.createByErrorCodeMessage(code, msg);
    }
}
